<?php

/**
 * TomatoCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version 	$Id: MenuController.php 4930 2010-08-25 03:38:40Z huuphuoc $
 * @since		2.0.2
 */
class Menu_MenuController extends Zend_Controller_Action {
    /* ========== Backend actions =========================================== */

    /**
     * Build new menu
     * 
     * @return void
     */
    public function buildAction() {
        $request = $this->getRequest();
        $menuModel = Rabbit_Model_Factory::getInstance()->setModule('menu')->getMenuModel();

        /**
         * @since 2.0.8
         */
        $sourceId = $request->getParam('source_id');
        $sourceMenu = (null == $sourceId) ? null : $menuModel->getById($sourceId);
        $this->view->assign('translatableData', (null == $sourceMenu) ? array() : $sourceMenu->getProperties());
        $this->view->assign('sourceMenu', $sourceMenu);
        $this->view->assign('lang', $request->getParam('lang'));
        /**
         * Added by TrongHM
         */
        $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
        $categoryModel->setLang($request->getParam('lang'));
        $categories = $categoryModel->getTree();
        $categorySet = array();
        foreach ($categories as $category) {
            if (!key_exists($category->module_name, $categorySet))
                $categorySet[$category->module_name] = array();
            $categorySet[$category->module_name][] = $category;
        }
        $this->view->assign('categorySet', $categorySet);

        $pageModel = Rabbit_Model_Factory::getInstance()->setModule('page')->getPageModel();
        $pageModel->setLang($request->getParam('lang'));
        $pages = $pageModel->getTree();
        $this->view->assign('pages', $pages);
        

        if ($request->isPost()) {
            $name = $request->getPost('name');
            $description = $request->getPost('description');
            $items = $request->getPost('items');

            $user = Zend_Auth::getInstance()->getIdentity();
            $menu = new Menu_Models_Entities_Menu(array(
                        'name' => $name,
                        'description' => $description,
                        'user_id' => $user->id,
                        'user_name' => $user->username,
                        'created_date' => date('Y-m-d H:i:s'),
                        /**
                         * @since 2.0.8
                         */
                        'language' => $request->getPost('language')
                    ));
            $menuId = $menuModel->add($menu);

            /**
             * @since 2.0.8
             */
            $source = Zend_Json::decode($request->getPost('sourceItem', '{"id": "", "language": ""}'));

            $translationModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
            $translationModel->add(new Core_Models_Entities_Translation(array(
                        'item_id' => $menuId,
                        'item_class' => get_class($menu),
                        'source_item_id' => ('' == $source['id']) ? $menuId : $source['id'],
                        'language' => $menu->language,
                        'source_language' => ('' == $source['language']) ? null : $source['language'],
                    )));

            /**
             * @since 2.0.7
             */
            if ($items != '') {
                $itemModel = Rabbit_Model_Factory::getInstance()->setModule('menu')->getItemModel();

                $items = Zend_Json::decode($items);
                foreach ($items as $item) {
                    $itemModel->update(new Menu_Models_Entities_Item(array(
                                'id' => $item['id'],
                                'label' => $item['label'],
                                'link' => $item['link'],
                                'menu_id' => $menuId,
                                'depth' => $item['depth'],
                                'ordering' => $item['ordering'],
                                'parent_id' => $item['parent_id'],
                                'target' => $item['target'],
                                'type' => $item['type']
                            )));
                }
            }

            $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('success:' . $this->view->translate('menu_build_success'));
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'menu_menu_build'));
        }
    }

    /**
     * Delete menu
     * 
     * @return void
     */
    public function deleteAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();
        $result = 'RESULT_ERROR';

        if ($request->isPost()) {
            $id = $request->getPost('id');
            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $menuModel = Rabbit_Model_Factory::getInstance()->setModule('menu')->getMenuModel();
            $menuModel->setDbConnection($conn);

            $menu = $menuModel->getById($id);
            if (null == $menu) {
                $this->getResponse()->setBody('RESULT_NOT_FOUND');
                return;
            }
            $menuModel->delete($id);

            /**
             * @since 2.0.8
             */
            $translationModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
            $translationModel->setDbConnection($conn);
            $translationModel->delete($id, get_class($menu));

            $result = 'RESULT_OK';
        }
        $this->getResponse()->setBody($result);
    }

    /**
     * Edit menu
     * 
     * @return void
     */
    public function editAction() {
        $request = $this->getRequest();
        $menuId = $request->getParam('id');
        $menuModel = Rabbit_Model_Factory::getInstance()->setModule('menu')->getMenuModel();
        $menu = $menuModel->getById($menuId);
        /**
         * Added by TrongHM
         */
        $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
        $categories = $categoryModel->getTree();
        $categorySet = array();
        foreach ($categories as $category) {
            if (!key_exists($category->module_name, $categorySet))
                $categorySet[$category->module_name] = array();
            $categorySet[$category->module_name][] = $category;
        }
        $this->view->assign('categorySet', $categorySet);

        $pageModel = Rabbit_Model_Factory::getInstance()->setModule('page')->getPageModel();
        $pages = $pageModel->getTree();
        $this->view->assign('pages', $pages);



        if (null == $menu) {
            throw new Exception('The menu with Id of ' . $menuId . ' does not exist');
        }

        $itemModel = Rabbit_Model_Factory::getInstance()->setModule('menu')->getItemModel();
        $items = $itemModel->getTree($menuId);
        $this->view->assign('menu', $menu);
        $this->view->assign('items', $items);
    
        /**
         * @since 2.0.8
         */
        $sourceMenu = $menuModel->getSource($menu);
        $this->view->assign('sourceMenu', $sourceMenu);
        
        if ($request->isPost()) {
            $name = $request->getPost('name');
            $description = $request->getPost('description');
            $items = $request->getPost('items');
            $menu->name = $name;
            $menu->description = $description;

            /**
             * @since 2.0.8
             */
            $menu->language = $request->getPost('language', $menu->language);

            $menuModel->update($menu);
            
            /**
             * @since 2.0.7
             */
            if ($items != '') {
                $itemModel = Rabbit_Model_Factory::getInstance()->setModule('menu')->getItemModel();

                $items = Zend_Json::decode($items);
               
                foreach ($items as $item) {

                    $itemModel->update(new Menu_Models_Entities_Item(array(
                                'id' => $item['id'],
                                'label' => $item['label'],
                                'link' => $item['link'],
                                'menu_id' => $menuId,
                                'depth' => $item['depth'],
                                'ordering' => $item['ordering'],
                                'parent_id' => $item['parent_id'],
                                'target' => $item['target'],
                                'type'  => $item['type']
                            )));
                }
//                $itemModel->delete($menuId);
//
//                $newItems = Zend_Json::decode($newItems);
//                foreach ($newItems as $item) {
//                    $itemModel->add(new Menu_Models_Item(array(
//                                'item_id' => $item['item_id'],
//                                'label' => $item['label'],
//                                'link' => $item['link'],
//                                'menu_id' => $menuId,
//                                'left_id' => $item['left_id'],
//                                'right_id' => $item['right_id'],
//                                'parent_id' => $item['parent_id'],
//                            )));
//                }
            }

            /**
             * @since 2.0.8
             */
            
            $source = Zend_Json::decode($request->getPost('sourceItem', '{"id": "", "language": ""}'));
            $translationModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
            $translationModel->update(new Core_Models_Entities_Translation(array(
                        'item_id' => $menuId,
                        'item_class' => get_class($menu),
                        'source_item_id' => ('' == $source['id']) ? $menuId : $source['id'],
                        'language' => $menu->language,
                        'source_language' => ('' == $source['language']) ? null : $source['language'],
                    )));
            
            $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('success:'.$this->view->translator('menu_edit_success'));
            $this->_redirect($this->view->serverUrl() . $this->view->url(array('id' => $menu->id), 'menu_menu_edit'));
        }
    }
        

    /**
     * List menus
     * 
     * @return void
     */
    public function listAction() {
        $request = $this->getRequest();
        $menuModel = Rabbit_Model_Factory::getInstance()->setModule('menu')->getMenuModel();

        $perPage = 20;
        $pageIndex = $request->getParam('pageIndex', 1);
        $offset = ($pageIndex - 1) * $perPage;

        /**
         * @since 2.0.8
         */
        $lang = $request->getParam('lang');
        $menuModel->setLang($lang);

        $menus = $menuModel->getMenus($offset, $perPage);
        $numMenus = $menuModel->count();

        /**
         * Paginator
         */
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($menus, $numMenus));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('menus', $menus);
        $this->view->assign('numMenus', $numMenus);

        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path' => $this->view->url(array(), 'menu_menu_list'),
            'itemLink' => 'page-%d',
        ));
    }

    /**
     * Add by tronghm
     */

    /**
     * Ajax to get Route of Category
     */
    public function routeAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $result = array('status' => 'failed', 'message' => '');
        $request = $this->getRequest();
        if ($request->isPost()) {

            $type = $request->getPost('type');
            //$model = $request->getPost('model');            
            $itemModel = Rabbit_Model_Factory::getInstance()->setModule('menu')->getItemModel();

            $item = null;

            switch ($type) {
                case 'category' :
                    $id = $request->getPost('id');
                    if ($id) {
                        $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
                        $category = $categoryModel->getById($id);
                        if ($category == null) {
                            //$result['message'] = $this->view->translate('category_not_found');
                        } else {
                            $properties = $category->getProperties();
                            $properties['category_id'] = $properties['id'];
                            switch ($category->module_name){
                                case 'news':
                                    $link = $this->view->url($properties, 'news_article_category');
                                    break;
                                case 'product':
                                    $link = $this->view->url($properties, 'product_product_category');
                                    break;
                                default:
                                    break;
                            }
                            $item = new Menu_Models_Entities_Item(array(
                                        'label' => $category->name,
                                        'link' => $link,
                                        'menu_id' => 0,
                                        'parent_id' => 0,
                                        'type' => 'category'
                                    ));
                            $item = $itemModel->add($item);
                        }
                    }
                    break;
                case 'page':
                    $id = $request->getPost('id');
                    if ($id) {
                        $pageModel = Rabbit_Model_Factory::getInstance()->setModule('page')->getPageModel();
                        $page = $pageModel->getById($id);

                        if ($page == null) {
                            //$result['message'] = $this->view->translate('category_not_found');
                        } else {
                            $item = new Menu_Models_Entities_Item(array(
                                        'label' => $page->name,
                                        'link' => $this->view->url($page->getProperties(), 'page_page_details'),
                                        'menu_id' => 0,
                                        'parent_id' => 0,
                                        'type' => 'page'
                                    ));
                            $item = $itemModel->add($item);
                        }
                    }
                    break;
                case 'custom':
                    $item = new Menu_Models_Entities_Item(array(
                                'label' => $request->getPost('label'),
                                'link' => $request->getPost('link'),
                                'menu_id' => 0,
                                'parent_id' => 0,
                                'type' => 'custom'
                            ));
                    $item = $itemModel->add($item);
                    break;
                default: break;
            }
            if ($item) {
                $result['status'] = 'ok';
                $result['item'] = new stdClass();
                $result['item']->id = $item->id;
                $result['item']->label = $item->label;
                $result['item']->parent_id = $item->parent_id;
                $result['item']->link = $item->link;
                $result['item']->ordering = $item->ordering;
            }
        }
        $this->getResponse()->setBody(Zend_Json::encode($result));
    }

    /**
     * Delete menu item
     * @author TrongHM 
     */
    public function deleteitemAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $result = array('status' => false, 'message' => '');
        $request = $this->getRequest();
        if ($request->isPost()) {
            $item_id = $request->getPost('id');
            $itemModel = Rabbit_Model_Factory::getInstance()->setModule('menu')->getItemModel();
            if ($itemModel->deleteById($item_id)) {
                $result['status'] = true;
            }
        }
        $this->getResponse()->setBody(Zend_Json::encode($result));
    }

//    public function edititemAction(){
//        $this->_helper->getHelper('layout')->disableLayout();
//        $this->_helper->getHelper('viewRenderer')->setNoRender();
//        $result = array('status' => false, 'message' => '');
//        $request = $this->getRequest();
//        if ($request->isPost()) {
//            $item = new Menu_Models_Entities_Item(
//                        array(
//                            'id' => $request->getPost('id'),
//                            'label' => $request->getPost('label'),
//                            'link'  => $request->getPost('link'),
//                            'target' => $request->getPost('target')
//                        ));
//            $itemId = $request->getPost('id');
//            
//            $itemModel  = Rabbit_Model_Factory::getInstance()->setModule('menu')->getItemModel();
//            if($itemModel->edit($itemId)){
//                $result['status'] = true;
//            }
//        
//        }
//    }
}
